package cn.foolishbird.business.tool.task;

import java.util.List;

/**
 * 多线程迭代任务
 *
 * @author Eric
 * @version 1.0
 * @date 2020-11-16
 */
public abstract class MultiThreadTaskIterator<T, N> extends AbstractTaskIterator<T> {

    /**
     * 线程数量
     */
    private int threadNum = 2;

    private TaskNoGenerator<N> taskNoGenerator;


    @Override
    public void iterator() {
        if (null == taskNoGenerator) {
            throw new RuntimeException("Task number generator is not initialize");
        }
        for (int i = 0; i < 2; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    List<T> list = next();
                    while (null != list && !list.isEmpty()) {
                        for (T t : list) {
                            execute.execute(t);
                        }
                        list = next();
                    }
                }
            });
            thread.start();
        }
    }

    @Override
    public List<T> next() {
        return doNext(taskNoGenerator.taskNo());
    }

    protected abstract List<T> doNext(N n);


    public int getThreadNum() {
        return threadNum;
    }

    public void setThreadNum(int threadNum) {
        this.threadNum = threadNum;
    }

    public TaskNoGenerator<N> getTaskNoGenerator() {
        return taskNoGenerator;
    }

    public void setTaskNoGenerator(TaskNoGenerator<N> taskNoGenerator) {
        this.taskNoGenerator = taskNoGenerator;
    }
}
